def test(fn):
= [2,7,11,15]
numbers = 9
target = (1,2)
expected assert fn(numbers,target) == expected
= [2,3,4]
numbers = 6
target = (1,3)
expected assert fn(numbers,target) == expected
= [-1,0]
numbers = -1
target = (1,2)
expected assert fn(numbers,target) == expected
Problem Source: Leetcode
Problem Description
Given a 1-indexed array of integers numbers
that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target
number. Let these two numbers be numbers[index1]
and numbers[index2]
where 1 <= index1 < index2 <= numbers.length
.
Return the indices of the two numbers, index1
and index2
, added by one as an integer array [index1, index2]
of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
tests
Solution
- Time Complexity:
O(1)
- Space Complexity:
O(n)
from typing import List
def twoSum(numbers: List[int], target: int) -> List[int]:
# start at each end of the list
= 0, len(numbers) - 1
i1, i2
while i1 < i2:
= numbers[i1] + numbers[i2]
curr_sum
if curr_sum < target: # If too small
+= 1 # make it bigger
i1 elif curr_sum > target: # If too big
-= 1 # make it smaller
i2 else:
return i1+1, i2+1 # if juuussstt right
test(twoSum)